<?php

require "../../types.php";
require "../../utility.php";
require "./book_utility.php";

function storeBookToDatabase(mysqli $conn, Book $book): bool {
    $insert_str = "INSERT INTO Book (title, author, publisher, category, price, imgURL) 
                              VALUES(  ?,      ?,      ?,         ?,       ?,      ?  );";
    $insert_stmt = $conn->prepare($insert_str);

    $insert_stmt->bind_param("ssssds", 
        $book->title,
        $book->author,
        $book->publisher,
        $book->category,
        $book->price,
        $book->img_url
    );

    return $insert_stmt->execute();
}

$conn = connect_mysql();
$user_id = getUserIdBySessionId($conn);

http_response_code(403);

if ($user_id !== null) {
    $require_permission = 1;
    $user_permission = getUserPermissionByUserId($conn, $user_id);

    // 检查权限以及必要的字段
    if ($user_permission >= $require_permission && 
        check_keys($_POST, "title", "author", "publisher", "category", "price")) {
        
        $book            = new Book;
        $book->title     = $_POST["title"];
        $book->author    = $_POST["author"];
        $book->publisher = $_POST["publisher"];
        $book->category  = $_POST["category"];
        $book->price     = $_POST["price"];
        $book->img_url   = storeImgToLocal();
        
        // 检查是否成功将图片保持到本地以及是否成功将书本保存到数据库中
        if ($book->img_url !== null &&
            storeBookToDatabase($conn, $book)) {
            // success
            http_response_code(200);

            // for debug
            echo $book->img_url;
        }
    }
}

?>